<?php

namespace app\common\model\xilumarket;

use think\Model;
use traits\model\SoftDelete;
use think\Cache;

class Area extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'xilumarket_area';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    public static function getNameById($id)
    {
        $area = self::getCacheAll();
        return $area[$id]['name'];
    }

    public static function getCacheAll()
    {
        return self::areaCache()['all'];
    }

    private static function areaCache()
    {
        if (!Cache::get('area')) {
            // 所有地区
            $all = $allData = self::useGlobalScope(false)->column('id, pid, name, level', 'id');

            // 格式化
            $tree = [];
            foreach ($allData as $pKey => $province) {
                if ($province['level'] === 1) {    // 省份
                    $tree[$province['id']] = $province;
                    unset($allData[$pKey]);
                    foreach ($allData as $cKey => $city) {
                        if ($city['level'] === 2 && $city['pid'] === $province['id']) {    // 城市
                            $tree[$province['id']]['city'][$city['id']] = $city;
                            unset($allData[$cKey]);
                            foreach ($allData as $rKey => $area) {
                                if ($area['level'] === 3 && $area['pid'] === $city['id']) {    // 地区
                                    $tree[$province['id']]['city'][$city['id']]['area'][$area['id']] = $area;
                                    unset($allData[$rKey]);
                                }
                            }
                        }
                    }
                }
            }
            Cache::set('area', compact('all', 'tree'));
        }
        return Cache::get('area');
    }

    public function children(){
        return $this->hasMany(self::class,'first','first');
    }
    public function childlist(){
        return $this->hasMany(self::class,'pid','id');
    }
    /**
     * 获取所有城市
     */
    public function getCityList()
    {
        $lists = $this->field(['first'])
            ->with(['children'=>function($query){
            $query->where('level',2)->where('status', 'normal')->field("id,name,first");
        }])->where('level', 2)->where('status', 'normal')->group('first')->order('first','asc')->select();
        return $lists;
    }
    /**
     * 根据城市获取其下区县、街道
     */
    public function getRegionStreet($city, $type = 1)
    {
        $city_id = $this->where('level', 2)->where('status', 'normal')->where('name', 'like', $city . '%')->value('id') ?: 0;
        if (!$city_id) {
            return [];
        }
        // 获取区县
        $areaList = $this->where('level', 3)->where('status', 'normal')->where('pid', $city_id)->select();
        if ($type == 1) {
            foreach ($areaList as $key => $value) {
                $areaList[$key]['list'] = $this->where('level', 4)->where('pid', $value['id'])->select();
            }
        }

        return $areaList;
    }

    /**
     * 根据经纬度获取城市
     * @param $lng
     * @param $lat
     * @return array|bool|false|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getCityFromLngLat($lng, $lat){
        $arr = xilumarketGetAddr($lat, $lng);
        if (isset($arr['city'])) {
            $city = self::where('level', 2)->where('status', 'normal')->where('name', 'like', $arr['city'] . '%')->field('id,name')->find() ?: '';
            return $city;
        } else {
            return [];
        }
    }


}
